package com.yangfan.screenshot.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

import com.yangfan.screenshot.log.LogUtil;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;

/**
 * @author : yangfan
 * @date : 2022/12/8-21:30
 * desc   :
 */
public final class BitmapUtil {

    /**
     * 位图保存到文件
     *
     * @param bitmap         位图
     * @param str            str
     * @param compressFormat 压缩格式
     */
    public static void saveBitmapToFile(Bitmap bitmap, String str, Bitmap.CompressFormat compressFormat) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(str);
            Bitmap createBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            new Canvas(createBitmap).drawBitmap(bitmap, (Rect) null, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()), null);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            createBitmap.compress(compressFormat, 100, byteArrayOutputStream);
            int i = 100;
            while (byteArrayOutputStream.toByteArray().length / 1024 > 2048) {
                byteArrayOutputStream.reset();
                i -= 10;
                createBitmap.compress(compressFormat, i, byteArrayOutputStream);
            }
            createBitmap.compress(compressFormat, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    /**
     * 两个bitmap合并成新的bitmap
     *
     * @param bitmap  位图
     * @param bitmap2 bitmap2
     * @return {@link Bitmap}
     */
    public static Bitmap mergeBitmap(Bitmap bitmap, Bitmap bitmap2) {
        if (bitmap == null || bitmap2 == null) {
            return null;
        }

        LogUtil.d("BitmapUtil","mergeBitmap getWidth = " + Math.max(bitmap.getWidth(), bitmap2.getWidth()) + "; getHeight = " + (bitmap.getHeight() + bitmap2.getHeight()));
        Bitmap createBitmap = Bitmap.createBitmap(Math.max(bitmap.getWidth(), bitmap2.getWidth()), bitmap.getHeight() + bitmap2.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(createBitmap);
        canvas.drawBitmap(bitmap, 0.0f, 0.0f, null);
        canvas.drawBitmap(bitmap2, 0.0f, bitmap.getHeight(), null);
        canvas.save();
        canvas.restore();
        return createBitmap;
    }

    public static Bitmap removeStatusbar(Bitmap bitmap) {
        int statusBarHeight = ScreenUtil.instance.getStatusBarHeight();
        return Bitmap.createBitmap(bitmap,0,statusBarHeight,bitmap.getWidth(),bitmap.getHeight() - statusBarHeight);
    }
}
